package com.study.dao.impl;

import com.study.bean.query.RecordQuery;
import com.study.bean.vo.RecordVo;
import com.study.dao.RecordDao;
import com.study.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class RecordDaoImpl implements RecordDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<RecordVo> selectByPage(RecordQuery recordQuery) {
        String sql = "select r.id,r.stu_id,r.dorm_id,r.build_id,r.cause,r.mtime,s.name 'sName' from record r inner join students s on r.stu_id = s.student_id where 1=1";
        List<Object> list = new ArrayList<>();
        if (recordQuery.getBuildId() != null) {
            sql += " and r.build_id = " + recordQuery.getBuildId();
        }
        if (recordQuery.getDormId() != null) {
            sql += " and r.dorm_id = " + recordQuery.getDormId();
        }
        if (recordQuery.getStuId() != null) {
            sql += " and r.stu_id = " + recordQuery.getStuId();
        }
        if (recordQuery.getSName() != null){
            sql += " and s.name like '%" + recordQuery.getSName() + "%'";
        }
        sql += " limit ?,?";
        int offset = (recordQuery.getPage() - 1) * recordQuery.getLimit();
        list.add(offset);
        list.add(recordQuery.getLimit());
        System.out.println(list);
        List<RecordVo> list1 = template.query(sql,
                new BeanPropertyRowMapper<>(RecordVo.class), list.toArray());
        list1.forEach(System.out::println);
        return list1;

    }

    @Override
    public int selectTotalCount(RecordQuery recordQuery) {
        String sql = "select count(*) from record where 1=1";
        if (recordQuery.getBuildId() != null) {
            sql += " and build_id = " + recordQuery.getBuildId();
        }
        if (recordQuery.getDormId() != null) {
            sql += " and dorm_id = " + recordQuery.getDormId();
        }
        if (recordQuery.getStuId() != null) {
            sql += " and stu_id = " + recordQuery.getStuId();
        }
        if (recordQuery.getSName() != null){
            sql += " and s.name like '%" + recordQuery.getSName() + "%'";
        }
        int count = template.queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public List<RecordVo> selectAll() {
        String sql = "select r.id,r.stu_id,r.dorm_id,r.build_id,r.cause,r.mtime,s.name 'sName' from record r inner join students s on r.stu_id = s.student_id ";
        List<RecordVo> list = template.query(sql,
                new BeanPropertyRowMapper<>(RecordVo.class));
        list.forEach(System.out::println);
        return list;
    }
}
